import React, { ReactNode, PureComponent, createRef } from 'react'
import BScroll from '@better-scroll/core'
import ScrollBar from '@better-scroll/scroll-bar'
import MouseWheel from '@better-scroll/mouse-wheel'
import { Song } from '@/types/common-types'
import { Lyric } from '@/utils/parse-lyric'
import './style.less'

interface IProps {
  children?: ReactNode
  data: Lyric[] | Song[]
  panelShow: boolean
  onScrollEnd: (y: number) => void
}

interface Position {
  x: number
  y: number
}

type ScrollToElProps = [
  el: any,
  time: number,
  x: number | boolean,
  y: number | boolean
]

BScroll.use(ScrollBar)
BScroll.use(MouseWheel)

class PlayerScroll extends PureComponent<IProps> {
  private scrollRef = createRef<any>()
  constructor(props: IProps, private bs: BScroll) {
    super(props)
  }
  componentDidMount() {
    this.bs = new BScroll(this.scrollRef.current, {
      scrollBar: {
        interactive: true
      },
      mouseWheel: {}
    })
    this.bs.on('scrollEnd', (pos: Position) => {
      this.props.onScrollEnd(pos.y)
    })
  }
  componentDidUpdate() {
    if (this.props.panelShow) {
      this.refreshScroll()
    }
  }
  refreshScroll() {
    if (this.bs) {
      setTimeout(() => {
        this.bs.refresh()
      }, 20)
    }
  }
  boundScrollTo(...args: ScrollToElProps) {
    this.bs.scrollToElement.call(this, ...args)
  }
  boundScrollToElement(...args: ScrollToElProps) {
    this.bs.scrollToElement.call(this, ...args)
  }
  scrollTo(...args: ScrollToElProps) {
    this.boundScrollTo(...args)
  }
  scrollToElement(...args: ScrollToElProps) {
    this.boundScrollToElement(...args)
  }
  render() {
    return (
      <div className="scroll-wrap" ref={this.scrollRef}>
        {this.props.children}
      </div>
    )
  }
}

export default PlayerScroll
